import { Column, Entity, JoinColumn, ManyToOne, OneToMany, PrimaryGeneratedColumn, ManyToMany } from 'typeorm'
import { UserEntity } from 'src/user/entities/user.entity'
import { RoleEntity } from 'src/role/entities/role.entity'
import { ApiProperty } from '@nestjs/swagger'

//用户和角色是多对多的关系，菜单和角色是多对多的关系，用户和菜单也是多对多的关系
//要三张表，三张关系表 用户分配角色继承角色的菜单
@Entity('menu')
export class MenuEntity {
  @PrimaryGeneratedColumn()
  id: number

  @ApiProperty({ description: '路由名称' })
  @Column()
  name: string

  @ApiProperty({ description: '路由路径' })
  @Column()
  path: string

  @ApiProperty({ description: '路由title' })
  @Column({ nullable: true })
  title: string

  @ApiProperty({ description: '路由icon' })
  @Column({ nullable: true })
  icon: string

  @ApiProperty({ description: '是否展示为菜单-- 菜单(展示)-1  页面(不展示)-0' })
  @Column({ type: 'tinyint', default: 1 })
  is_menu: number

  @ApiProperty({ description: '是否为按钮权限-- 页面权限-1  按钮权限-0' })
  @Column({ type: 'tinyint', default: 1 })
  auth_type: number

  @ApiProperty({ description: '一级菜单标识' })
  @Column({ type: 'tinyint', default: 0 })
  first_menu: number

  // 父级菜单为多对一关系
  @OneToMany(() => MenuEntity, (menu) => menu.parent)
  children: MenuEntity[]

  //自关联子表
  @ManyToOne(() => MenuEntity, (menu) => menu.children, { cascade: true, onDelete: 'CASCADE' })
  @JoinColumn()
  parent: MenuEntity

  //多对多关联用户
  @ApiProperty({ description: '菜单权限与用户可以是多对多' })
  @ManyToMany(() => UserEntity, (user) => user.menus)
  users: UserEntity[]

  @ApiProperty({ description: '菜单权限与角色可以是多对多' })
  @ManyToMany(() => RoleEntity, (role) => role.menus)
  roles: RoleEntity[]

  @Column({ type: 'timestamp', name: `create_time`, default: () => 'CURRENT_TIMESTAMP' })
  createTime: Date

  @Column({ type: 'timestamp', name: `update_time`, default: () => 'CURRENT_TIMESTAMP' })
  updateTime: Date
}
